package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * GetResponseNormal类
 * 实现普通读取响应的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class GetResponseNormal implements AxdrType {

    private byte[] dataCode = null;
    private PIID piidAcd = null;
    private A_ResultNormal result = null;

    /**
     * 默认构造函数
     */
    public GetResponseNormal() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置所有参数
     * 
     * @param piidAcd 协议标识符和访问控制位
     * @param result  结果
     */
    public void setAll(PIID piidAcd, A_ResultNormal result) {
        this.piidAcd = piidAcd;
        this.result = result;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        piidAcd = new PIID();
        piidAcd.setNumBit(8);
        codeLength += piidAcd.decode(input);

        result = new A_ResultNormal();
        codeLength += result.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            }
        } else {
            if (piidAcd != null && result != null) {
                codeLength = 0;
                codeLength += result.encode(output);
                codeLength += piidAcd.encode(output);
            } else {
                throw new RuntimeException("piid_acd || result is null");
            }
        }
        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (piidAcd != null && result != null) {
            return "sequence: {" + "piid_acd: " + piidAcd + ", result: " + result + "}";
        } else {
            return "piid_acd || result is null";
        }
    }

    // 添加getter方法
    public PIID getPiidAcd() {
        return this.piidAcd;
    }

    public A_ResultNormal getResult() {
        return this.result;
    }
}